<template>
  <ContentWrap class="!mb-0">
    <!-- 搜索工作栏 -->
    <el-form
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
      label-position="left"
    >
      <el-form-item label="分组名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入分组名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-260px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['crm:module:update']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <el-table v-loading="loading" :data="listData" border class="m-20px mt-0">
    <el-table-column label="分组名称" align="center" prop="name" width="200" />
    <el-table-column label="标签" align="left" prop="name">
      <template #default="scope">
        <div class="cusomerTag py-8px">
          <el-tag
            v-for="tag in scope.row.labelList"
            :key="tag.id"
            checked
            :closable="true"
            :disable-transitions="false"
            @close="handleClose(tag.id)"
            :style="{
              background: tag.bgColor,
              color: tag.textColor,
              marginRight: '10px',
              border: 'none',
              cursor: 'pointer',
              paddingRight: '9px'
            }"
            @click="openFormTag('update', tag.id)"
            >{{ tag.name }}</el-tag
          >
          <el-button
            link
            type="primary"
            v-hasPermi="['crm:module:update']"
            @click="openFormTag('create', scope.row.id)"
          >
            新增
          </el-button>
        </div>
      </template>
    </el-table-column>
    <el-table-column label="备注" align="center" prop="remark" width="200" />

    <el-table-column
      label="创建时间"
      align="center"
      prop="createTime"
      :formatter="dateFormatter"
      width="180px"
    />
    <el-table-column label="操作" align="center" width="130">
      <template #default="scope">
        <el-button
          link
          type="primary"
          @click="openForm('update', scope.row.id)"
          v-hasPermi="['crm:module:update']"
        >
          编辑
        </el-button>
        <el-button
          link
          type="danger"
          @click="handleDelete(scope.row.id)"
          v-hasPermi="['crm:module:update']"
        >
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <Pagination
    :total="totals"
    v-model:page="queryParams.pageNo"
    v-model:limit="queryParams.pageSize"
    @pagination="getList"
  />

  <!-- 表单弹窗：添加/修改 -->
  <TagGroupConfigForm ref="formRef" @success="getList" />
  <!-- 标签弹窗：添加/修改 -->
  <TagConfigForm ref="formTagRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import * as customerTagApi from '@/api/crm/customerTagConfig/index'
import TagGroupConfigForm from './TagGroupConfigForm.vue'
import TagConfigForm from './TagConfigForm.vue'
import { color } from 'echarts'

defineOptions({ name: 'CustomerTagConfig' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const listData = ref<any[]>([]) // 列表的数据
const totals = ref(0)

const queryParams = reactive({
  name: null,
  pageNo: 1,
  pageSize: 10
})
const queryFormRef = ref() // 搜索的表单

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const { list, total } = await customerTagApi.getCustomerTagPageDefault(queryParams)
    listData.value = list
    totals.value = total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const formTagRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await customerTagApi.deletelabelDefault(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}
/*标签集新增*/
const openFormTag = (type: string, id?: number) => {
  formTagRef.value.open(type, id)
}

const handleClose = (id: string) => {
  ElMessageBox.confirm(
    '删除标签后，相应的线索和客户中的此标签也会被删除，且无法恢复。',
    '确认删除标签？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      const res = await customerTagApi.deleteTagDefault(id)
      if (res) ElMessage.success('删除成功!')
      getList()
    })
    .catch(() => {})
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
<style scoped lang="scss">
::v-deep(.el-check-tag) {
  padding: 1px 8px 3px;
  font-size: 12px;
}

::v-deep(.is-closable) {
  position: relative;
  .el-tag__close {
    display: none;
    position: absolute;
    right: -10px;
    top: -5px;
    color: #fff;
    background-color: red;
  }
}
::v-deep(.is-closable):hover {
  .el-tag__close {
    display: flex;
  }
}
</style>
